<template>
  <div>
    <el-row class="secondRow">
      <el-button type="primary" @click="(showTopBannerDialog = true), (dialogType = 0)">新增顶部大BANNER</el-button>
      <el-button
        type="primary"
        @click="(showFootBannerDialog = true), (dialogFootType = 0)"
      >新增底部BANNER</el-button>
    </el-row>
    <el-row>
      <el-table
        ref="filterTable"
        :data="tableData"
        tooltip-effect="dark"
        :default-sort="{prop: 'sort', order: 'ascending'}"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        row-key="id"
        id="out-table"
        @filter-change="filterChange"
      >
        <el-table-column prop="id" label="ID" width="50"></el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column min-width="120" prop="thumbnail" label="图片链接" align="center">
          <template slot-scope="scope">
            <a :href="scope.row.thumbnail|getStaticImg" target="_blank">
              <img style="width:150px;border:none;" :src="scope.row.thumbnail|getStaticImg" />
            </a>
          </template>
        </el-table-column>
        <el-table-column prop="link,link_id" label="跳转ID/链接">
          <template slot-scope="scope">
            <span v-if="scope.row.link_type == 1">
              分类id：{{ scope.row.link_id }}
              <br />
              {{ scope.row.link_name }}
            </span>
            <span v-if="scope.row.link_type == 2">
              标签id：{{ scope.row.link_id }}
              <br />
              {{ scope.row.link_name }}
            </span>
            <span v-if="scope.row.link_type == 3">
              专题id：{{ scope.row.link_id }}
              <br />
              {{ scope.row.link_name }}
            </span>
            <span v-if="scope.row.link_type == 4">链接:{{ scope.row.link }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="50"></el-table-column>
        <el-table-column
          prop="position"
          label="banner位置"
          :filters="positionOptions"
          filter-placement="bottom-end"
          column-key="position"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.position==1?'warning':'info'"
              disable-transitions
            >{{scope.row.position|homePositionFilter(positionOptions)}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="150" column-key="status">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.statusBool"
              active-text="开启"
              inactive-text="关闭"
              @change="bannerStatusChange($event, scope.row.id)"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="
                scope.row.position == '1'
                  ? editBanner(scope.row)
                  : editFootBanner(scope.row)
              "
            >编辑</el-button>
            <el-button type="text" size="small" @click="deleteBanner(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div class="block" style="margin-top:15px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[5, 10, 15, 20, 25, 30]"
          :page-size="pageSize"
          :pager-count="7"
          layout="sizes, prev, pager, next,jumper, ->,total"
          :total="count"
        ></el-pagination>
      </div>
    </el-row>

    <!-- 新增/编辑顶部大BANNER -->
    <el-dialog
      title="新增/编辑顶部大BANNER"
      :visible.sync="showTopBannerDialog"
      :close-on-click-modal="false"
      :before-close="resetEdit"
    >
      <el-form :model="editForm" :rules="rules" ref="topBanner">
        <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
          <el-input v-model="editForm.title" autocomplete="off" @change="checktitle('0')"></el-input>
        </el-form-item>
        <el-form-item label="跳转链接" :label-width="formLabelWidth" prop="thumbnail">
          <el-upload
            class="avatar-uploader"
            :action="uploadImageUrl"
            accept="image/jpeg, image/png, image/jpg"
            :show-file-list="false"
            :with-credentials="true"
            :on-success="handleAvatarSuccess"
            :data="{'pos':0,'dir':'banner'}"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="editForm.thumbnail"
              style="width:150px;border:none;"
              :src="editForm.thumbnail|getStaticImg"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetEdit">取 消</el-button>
        <el-button
          type="primary"
          :loading="button_loading"
          @click="dialogType === 0 ? addBanner('topBanner') : updateBanner('topBanner')"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!--新增/编辑底部BANNER-->
    <el-dialog
      title="新增/编辑底部BANNER"
      :visible.sync="showFootBannerDialog"
      :close-on-click-modal="false"
      :before-close="resetFootEdit"
    >
      <el-form :model="editFootForm" ref="footBanner" :rules="rules">
        <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
          <el-input
            v-model="editFootForm.title"
            autocomplete="off"
            placeholder="请输入标题"
            @change="checktitle('1')"
          ></el-input>
        </el-form-item>
        <el-form-item label="添加专题图片" :label-width="formLabelWidth" prop="thumbnail">
          <el-upload
            class="avatar-uploader"
            :action="uploadImageUrl"
            accept="image/jpeg, image/png, image/jpg"
            :show-file-list="false"
            :with-credentials="true"
            :on-success="handleAvatarSuccess"
            :data="{'pos':0,'dir':'banner'}"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="editFootForm.thumbnail"
              style="width:150px;border:none;"
              :src="editFootForm.thumbnail|getStaticImg"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="跳转类型" :label-width="formLabelWidth" prop="link_type">
          <el-select
            v-model="editFootForm.link_type"
            placeholder="请选择跳转类型"
            style="width:100%"
            @change="changeTypes"
          >
            <el-option
              v-for="item in changeOptions"
              :key="item.link_type"
              :label="item.label"
              :value="item.link_type"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="editFootForm.link_type==4"
          label="跳转链接"
          :label-width="formLabelWidth"
          prop="link"
        >
          <el-input v-model="editFootForm.link" autocomplete="off" placeholder="请输入跳转链接"></el-input>
        </el-form-item>
        <el-form-item
          v-if="editFootForm.link_type!=4"
          :label="editFootForm.link_type==1?'跳转分类':editFootForm.link_type==2?'跳转标签':editFootForm.link_type==3?'跳转专题':''"
          :label-width="formLabelWidth"
          prop="link_name"
        >
          <el-autocomplete
            v-model="editFootForm.link_name"
            v-if="editFootForm.link_type==1"
            style="width:100%;"
            :fetch-suggestions="queryCategory"
            placeholder="请输入分类id或名称"
            @select="handleSelectLink"
          ></el-autocomplete>
          <el-autocomplete
            v-model="editFootForm.link_name"
            v-if="editFootForm.link_type==2"
            style="width:100%;"
            :fetch-suggestions="queryTags"
            placeholder="请输入标签id或名称"
            @select="handleSelectLink"
          ></el-autocomplete>
          <el-autocomplete
            v-model="editFootForm.link_name"
            v-if="editFootForm.link_type==3"
            style="width:100%;"
            :fetch-suggestions="queryTopic"
            placeholder="请输入专题id或名称"
            @select="handleSelectLink"
          ></el-autocomplete>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetFootEdit">取 消</el-button>
        <el-button
          type="primary"
          :loading="button_loading"
          @click="dialogFootType === 0 ? addFootBanner('footBanner') : updateFootBanner('footBanner')"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Cookies from 'js-cookie'
import Sortable from "sortablejs";
import { typeSelects } from "@/utils/sel_dict";
import { queryCategory, queryTags, queryTopic } from "@/utils/query";

export default {
  name: "HeaderSearch",
  data() {
    return {
      positionOptions: [
        {
          text: "顶部大banner",
          value: 1,
          label: "顶部大banner"
        },
        {
          text: "底部banner",
          value: 2,
          label: "底部banner"
        }
      ],
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        thumbnail: [{ required: true, message: "请选择图片", trigger: "change" }],
        link_type: [
          { required: true, message: "请选择跳转类型", trigger: "change" }
        ],
        link: [{ required: true, message: "请输入链接", trigger: "change" }],
        link_name: [
          {
            required: true,
            message: "请输入跳转类型ID/链接",
            trigger: "change"
          }
        ]
        
      },
      changeOptions: typeSelects,
      uploadImageUrl: `${process.env.VUE_APP_BASE_API}/up/uploadlink?_csrf=${Cookies.get('X-CSRF-TOKEN')}`,
      showCategory: false,
      showTags: false,
      showLink: false,
      showTopic: false,
      categoryData: [], // 分类选项
      selectCategory: [], //存放分类选中项
      selectTags: [], //存放标签选中项
      selectTopic: [], //存放专题选中项
      showTopBannerDialog: false,
      showFootBannerDialog: false,
      dialogType: 0,
      dialogFootType: 0,
      formLabelWidth: "120px",
      // 分页
      pno: 1, //默认第一页
      pageSize: 15, //每页大小默认值
      where: {
        position: ""
      },
      editForm: {
        id: "",
        thumbnail: "",
        title: ""
      },
      editFootForm: {
        thumbnail: "",
        id: "",
        title: "",
        link: "", //跳转链接
        link_id: "", //对应跳转类型的id
        link_name: "", //对应跳转类型的id的名称
        link_type: "" //链接类型
      },
      tableData: [],
      count: 0,
      checkAll: false,
      isIndeterminate: true,
      button_loading: false //确定提交时加载状态
    };
  },
  mounted() {
    this.rowDrop();
    this.loaddata({
      page: this.pno,
      pagesize: this.pageSize,
      where: this.where
    });
  },
  methods: {
    queryCategory(...args) {
      return queryCategory.call(this, ...args);
    },
    queryTags(...args) {
      return queryTags.call(this, ...args);
    },
    queryTopic(...args) {
      return queryTopic.call(this, ...args);
    },
    filterChange(filterObj) {
      this.where.position = filterObj.position;
      this.loaddata({
        page: this.pno,
        pagesize: this.pageSize,
        where: this.where
      });
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
    },
    //检查标题
    checktitle(params) {
      var title_value = "";
      if (params == "0") {
        title_value = this.editForm.title;
      } else {
        title_value = this.editFootForm.title;
      }

      if (title_value != null && title_value != "") {
        this.axios
          .get("/banner/checkTitle", { params: { title: title_value } })
          .then(res => {
            if (res.length > 0) {
              this.$message.error("标题不能与之前的重复");
              if (params == "0") {
                this.editForm.title = "";
              } else {
                this.editFootForm.title = "";
              }
            }
          });
      }
    },
    checkSort(params) {
      var sort_value = "";
      if (params == "0") {
        sort_value = this.editForm.sort;
      } else {
        sort_value = this.editFootForm.sort;
      }
      if (sort_value != null && sort_value != "") {
        this.axios
          .get("/banner/checkSort", { params: { sort: sort_value } })
          .then(res => {
            if (res.length > 0) {
              this.$message.error("排序与之前的重复");
              if (params == "0") {
                this.editForm.sort = "";
              } else {
                this.editFootForm.sort = "";
              }
            }
          });
      }
    },
    rowDrop() {
      const tbody = document.querySelector(".el-table__body-wrapper tbody");
      const _this = this;
      Sortable.create(tbody, {
        draggable: ".el-table__row",
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.tableData.splice(oldIndex, 1)[0];
          _this.tableData.splice(newIndex, 0, currRow);
          _this.axios
            .post("/banner/bannerSort", {
              params: {
                start: newIndex,
                end: oldIndex
              }
            })
            .then(res => {
              if (res != undefined) {
                _this.loaddata({
                  page: _this.pno,
                  pagesize: _this.pageSize,
                  where: _this.where
                });
              }
            });
        }
      });
    },

    //更改跳转分类类型,每次选择清空上次选择
    changeTypes() {
      this.editFootForm.link = "";
      this.editFootForm.link_id = "";
      this.editFootForm.link_name = "";
    },
    //选中某个ID跳转
    handleSelectLink(item) {
      if (item.id == -1) {
        this.editFootForm.link_id = "";
        this.editFootForm.link_name = "";
        return;
      }
      this.editFootForm.link_id = item.id;
      this.editFootForm.link = "";
    },
    handleAvatarSuccess(res) {
      this.editForm.thumbnail = res.title;
      this.editFootForm.thumbnail = res.title;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    //加载banner列表
    loaddata(data) {
      this.axios
        .post("/banner/list", data)
        .then(res => {
          this.count = res.count;
          for (let row of res.rows) {
            row.statusBool = row.status == 0;
          }
          this.tableData = res.rows;
        })
        .catch(() => {
          this.$message.error("获取列表失败");
        });
    },
    //删除banner
    deleteBanner(params) {
      this.axios
        .post("/banner/deleteBanner", params)
        .then(res => {
          if (res.code == 200) {
            this.loaddata({
              page: this.pno,
              pagesize: this.pageSize,
              where: this.where
            });
            this.$message.info("删除成功");
          }
        })
        .catch(() => {
          this.$message.error("删除失败");
        });
    },
    //编辑底部banner
    editFootBanner(params) {
      this.dialogFootType = 1;
      Object.assign(this.editFootForm, params);
      this.showFootBannerDialog = true;
    },

    //新增底部banner
    addFootBanner(footBanner) {
      this.button_loading = true;
      this.$refs[footBanner].validate(valid => {
        if (valid) {
          if (
            this.editFootForm.link_type !== 4 &&
            this.editFootForm.link_id == ""
          ) {
            this.$message.error("请选择具体的跳转id");
            this.button_loading = false;
            return false;
          }
          this.axios
            .post("/banner/addFootBanner", this.editFootForm)
            .then(res => {
              if (res) {
                this.showFootBannerDialog = false;
                this.button_loading = false;
                this.resetFootEdit();
                this.loaddata({
                  page: this.pno,
                  pagesize: this.pageSize,
                  where: this.where
                });
                this.$message.success("添加成功");
              }
            })
            .catch(() => {
              this.showFootBannerDialog = false;
              this.button_loading = false;
              this.$message.error("添加失败");
            });
        } else {
          this.button_loading = false;
        }
      });
    },
    //新增顶部banner
    addBanner(topBanner) {
      this.button_loading = true;
      this.$refs[topBanner].validate(valid => {
        if (valid) {
          this.axios
            .post("/banner/addBanner", this.editForm)
            .then(res => {
              if (res != undefined) {
                this.showTopBannerDialog = false;
                this.button_loading = false;
                this.resetEdit();
                this.loaddata({
                  page: this.pno,
                  pagesize: this.pageSize,
                  where: this.where
                });
                this.$message.success("添加成功");
              }
            })
            .catch(() => {
              this.showTopBannerDialog = false;
              this.button_loading = false;
              this.$message.error("添加失败");
            });
        }
      });
    },
    bannerStatusChange(v, id) {
      if (!v) {
        this.bannerOff(id);
      } else {
        this.bannerUp(id);
      }
    },
    //关闭
    bannerOff(val) {
      this.axios
        .get("/banner/bannerOff", { params: { id: val } })
        .then(res => {
          if (res[0] > 0) {
            this.loaddata({
              page: this.pno,
              pagesize: this.pageSize,
              where: this.where
            });
            this.$message.info("已关闭");
            this.loaddata();
          }
        })
        .catch(() => {
          this.$message.error("关闭失败");
        });
    },
    //开启
    bannerUp(val) {
      this.axios
        .get("/banner/bannerUp", { params: { id: val } })
        .then(res => {
          if (res[0] > 0) {
            this.loaddata({
              page: this.pno,
              pagesize: this.pageSize,
              where: this.where
            });
            this.$message.info("已开启");
            this.loaddata();
          }
        })
        .catch(() => {
          this.$message.error("开启失败");
        });
    },
    //顶部大Banner编辑框显示
    editBanner(params) {
      this.dialogType = 1;
      this.showTopBannerDialog = true;
      Object.assign(this.editForm, params);
    },
    //提交编辑顶部大Banner
    updateBanner(topBanner) {
      this.$refs[topBanner].validate(valid => {
        if (valid) {
          this.axios
            .post("/banner/updateBanner", this.editForm)
            .then(res => {
              if (res[0] > 0) {
                this.showTopBannerDialog = false;
                this.resetEdit();
                this.$message.info("更新成功");
              } else {
                this.$message.info("您没有任何更改");
              }
            })
            .catch(() => {
              this.$message.error("更新失败");
            });
        }
      });
    },
    //提交编辑底部banner
    updateFootBanner(footBanner) {
      this.button_loading = true;
      this.$refs[footBanner].validate(valid => {
        if (valid) {
          if (
            this.editFootForm.link_type !== 4 &&
            this.editFootForm.link_id == ""
          ) {
            this.$message.error("请选择具体的跳转id");
            this.button_loading = false;
            return false;
          }
          this.axios
            .post("/banner/updateFootBanner", this.editFootForm)
            .then(res => {
              if (res) {
                this.showFootBannerDialog = false;
                this.button_loading = false;
                this.resetFootEdit();
                this.$message.info("更新成功");
              }
            })
            .catch(() => {
              this.button_loading = false;
              this.$message.error("更新失败");
            });
        } else {
          this.showFootBannerDialog = false;
        }
      });
    },
    initResetEdit() {
      return (this.editForm = {
        id: "",
        thumbnail: "",
        title: ""
      });
    },
    initResetFootEdit() {
      return (this.editFootForm = {
        thumbnail: "",
        id: "",
        title: "",
        link: "", //跳转链接
        link_id: "", //对应跳转类型的id
        link_name: "", //对应跳转类型的id的名称
        link_type: "" //链接类型
      });
    },
    //Topbanner编辑框清空
    resetEdit() {
      this.initResetEdit()
      this.showTopBannerDialog = false;
      this.$refs.topBanner.resetFields();
      this.loaddata({
        page: this.pno,
        pagesize: this.pageSize,
        where: this.where
      });
      this.button_loading=false
    },
    //Footbanner编辑框清空
    resetFootEdit() {
      this.initResetFootEdit()
      this.showFootBannerDialog = false;
      this.showCategory = false;
      this.showTags = false;
      this.showLink = false;
      this.showTopic = false;
      this.loaddata({
        page: this.pno,
        pagesize: this.pageSize,
        where: this.where
      });
      this.button_loading=false
      this.$refs.footBanner.resetFields();
    },
    handleCurrentChange(val) {
      this.pno = val;
      this.loaddata({
        page: this.pno,
        pagesize: this.pageSize,
        where: this.where
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.loaddata({
        page: this.pno,
        pagesize: this.pageSize,
        where: this.where
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.selectedIds = this.getSelectIds(this.selected);
      this.selectedLabels = this.makeTags(this.selected);
    },
    getSelectIds(val) {
      var ids = [];
      for (var obj of val) {
        ids.push(obj.id);
      }
      return ids;
    }
  }
};
</script>
<style lang="scss" scoped>
.el-table .status {
  white-space: normal;
  text-align: center;
}

.el-table .cell {
  white-space: normal !important;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}

.el-icon-arrow-down {
  font-size: 12px;
}

.demonstration {
  display: block;
  color: #8492a6;
  font-size: 14px;
  margin-bottom: 20px;
}

.secondRow {
  margin-top: 0px;
  margin-bottom: 15px;

  .el-dropdown:not(:first-child) {
    margin-left: 15px;
  }

  .el-dropdown {
    width: 160xp;
    padding: 5.5px 15px;
    border-radius: 3px;
    color: #fff;
    background-color: #476dbe;
    border-color: #476dbe;

    .el-dropdown-link[data-v-5110e31c] {
      color: #fff;
    }
  }
}
</style>